import { log } from 'node:console';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

import { type PluginOption } from 'vite';

/**
 * 用于生成将loading样式注入到项目中
 *
 */
async function viteInjectAppLoadingPlugin(loadingTemplate: string = 'loading.html'): Promise<PluginOption | undefined> {
    const loadingHtml = await getLoadingRawByHtmlTemplate(loadingTemplate);

    if (!loadingHtml) return;

    return {
        name: 'vite:inject-app-loading',
        enforce: 'pre',
        transformIndexHtml: {
            handler(html) {
                const re = /<body\s*>/;

                html = html.replace(re, `<body>${loadingHtml}`);

                return html;
            },
            order: 'post',
        },
    };
}

/**
 * 用于获取loading的html模板
 */
async function getLoadingRawByHtmlTemplate(loadingTemplate: string) {
    // 可以在根目录配置loading.html
    let appLoadingPath = join(process.cwd(), loadingTemplate);

    if (!fs.existsSync(appLoadingPath)) {
        const __dirname = fileURLToPath(new URL('.', import.meta.url));

        appLoadingPath = join(__dirname, loadingTemplate);
        // console.log(appLoadingPath, 'appLoadingPath');
    }

    return await fsp.readFile(appLoadingPath, 'utf8');
}

export { viteInjectAppLoadingPlugin };
